//
//  PhoneNumberViewController.swift
//  Hyphenate-Demo-Swift
//
//  Created by JennyShi on 2018/5/13.
//  Copyright © 2018年 curtainups. All rights reserved.
//

import UIKit
import os.log
import Hyphenate
import MobileCoreServices
import MBProgressHUD
import Alamofire

class PhoneNumberViewController: UIViewController, UITextFieldDelegate, UINavigationControllerDelegate{

    var username = ""
    var phone = ""
    var phoneCode = ""
    
    var countryCodeLabel = UILabel()
    var countryCode = UITextField()
    var prephoneLabel = UILabel()
    var phoneLabel = UILabel()
    var phoneView = UITextField()
    var phoneCodeView = UITextField()
    
    var sendButtonPhone = UIButton()
    var countdownTimer: Timer?
    var isCounting = false {
        willSet {
            if newValue {
                countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
                remainingSeconds = 60
                sendButtonPhone.backgroundColor = UIColor.gray
                getCode()
                print("\(remainingSeconds)")
            } else {
                countdownTimer?.invalidate()
                countdownTimer = nil
                sendButtonPhone.backgroundColor = UIColor.blue
            }
            sendButtonPhone.isEnabled = !newValue
        }
    }
    var remainingSeconds: Int = 0 {
        willSet {
            sendButtonPhone.setTitle(EnStatic.getWord(keyWord: "code sent") + "(\(newValue)" + EnStatic.getWord(keyWord: "seconds for new code") + ")", for: .normal)
            if newValue <= 0 {
                sendButtonPhone.setTitle(EnStatic.getWord(keyWord: "get new code"), for: .normal)
                isCounting = false
            }
        }
    }
    
    //屏幕不含状态栏的大小
    var screenX : Int = 0
    var screenY : Int = 0
    var screenWidth : Int = 0
    var screenHeight : Int = 0
    
    var widthEverage : Int = 0
    var heightEverage : Int = 0
    
    //控制状态变量
    var alertCancel = 0
    var alertOk = 0
    var requestHowManyTimes = 0
    var uploadCompleted = true
    
    //临时变量
    var statusPara = StatusPara(hasFriend:false,friendOwner:"",loginOwner:"",sourceViewControllerType:1,dateTitle:"",date:Date(),calendarTypeNumber:0,matchOrFree:0,languageNow:"")
    var loginOwner = ""
    var friendOwner = ""
    var date = Date()
    var dformatter = DateFormatter()
    var dateTitle = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //获得手机正在使用的语言
        let languageNow = EnStatic.languegeUsing()
        //login的owner的userid
        loginOwner = EMClient.shared().currentUsername
        dformatter = DateFormatter()
        dformatter.dateFormat = "yyyy-MM-dd"
        dateTitle = dformatter.string(from: date)
        statusPara = StatusPara(hasFriend:(!friendOwner.isEmpty),friendOwner:friendOwner,loginOwner:loginOwner,sourceViewControllerType:1,dateTitle:dateTitle,date:date,calendarTypeNumber:0,matchOrFree:0,languageNow:languageNow)
        
        //获取屏幕大小
        let selfViewBounds:CGRect = self.view.bounds
        let navigationHeight = UIApplication.shared.statusBarFrame.height
        
        screenX = Int(selfViewBounds.origin.x)
        screenY = Int(selfViewBounds.origin.y + navigationHeight)
        screenHeight = Int(selfViewBounds.height)
        screenWidth = Int(selfViewBounds.width)
        
        //自定义导航栏左侧的cancel按钮和右侧的save按钮
        let cancelButtonItem = UIBarButtonItem(title: EnStatic.getWord(keyWord: "Back"), style: .plain, target: self, action: #selector(cancelButtonClicked))
        self.navigationItem.leftBarButtonItem = cancelButtonItem
        
        let save000ButtonItem = UIBarButtonItem(title: EnStatic.getWord(keyWord: "Save"), style: .plain, target: self, action: #selector(saveButtonBigClicked))
        self.navigationItem.rightBarButtonItem = save000ButtonItem
        
        //获取旧的profile
        getProfile()
        
        //重新定义各个显示控件的尺寸、位置、颜色、形状等属性
        adapterUIAttribute()
        
        //设置textField和textView的代理
        countryCode.delegate = self
        phoneView.delegate = self
        phoneCodeView.delegate = self
        countryCode.returnKeyType = UIReturnKeyType.done
        phoneView.returnKeyType = UIReturnKeyType.done
        phoneCodeView.returnKeyType = UIReturnKeyType.done

        //设置save按钮状态
        updateSaveButtonState()
        
        //键盘弹出后textField位置移动
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(keyboardWillChange(_:)),
                                               name: .UIKeyboardWillChangeFrame, object: nil)
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // 键盘改变
    @objc func keyboardWillChange(_ notification: Notification) {
        if let userInfo = notification.userInfo,
            let value = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue,
            let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? Double,
            let curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? UInt {
            
            let oldFrame = phoneView.frame

            let frame = value.cgRectValue
            let intersection = frame.intersection(self.view.frame)
            let keyboardHeight = intersection.height
            let offset = keyboardHeight - keyboardHeight
            
            //根据键盘高度改变字段位置（此处没有改变，因为没有得到字段的名字，无法定位是在修改哪个字段）
            phoneView.frame = CGRect(x: oldFrame.origin.x, y: oldFrame.origin.y - offset, width: oldFrame.width, height: oldFrame.height)
            
            UIView.animate(withDuration: duration, delay: 0.0,
                           options: UIViewAnimationOptions(rawValue: curve), animations: {
                            
                            self.view.layoutIfNeeded()
            }, completion: nil)
        }
    }
    
    @objc func sendButtonPhoneClick(sender: UIButton) {
        print("ask for phone code")
        // 启动倒计时
        isCounting = true
    }
    
    @objc func updateTime(timer: Timer) {
        // 计时开始时，逐秒减少remainingSeconds的值
        remainingSeconds -= 1
    }
    
    //MARK: 限制只能输入数字
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let aSet = NSCharacterSet(charactersIn:"0123456789+").inverted
        let compSepByCharInSet = string.components(separatedBy: aSet)
        let numberFiltered = compSepByCharInSet.joined(separator: "")
        return string == numberFiltered
    }

    func myAlert(message000 : String) {
        let alertController = UIAlertController(title: "",message: EnStatic.getWord(keyWord: message000), preferredStyle: .alert)
        let okAction = UIAlertAction(title: EnStatic.getWord(keyWord: "OK"), style: .default, handler: {
            action in
            print("ok clicked")
        })
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil)
    }
    
    //MARK: 导航栏左上角的cancel返回键和右上角的save返回键
    @objc func cancelButtonClicked() {
        if let owningNavigationController = self.navigationController{
            owningNavigationController.popViewController(animated: true)
        }else {
            fatalError("The ViewController is not inside a navigation controller.")
        }
    }
    
    @objc func saveButtonBigClicked() {
        
        postCode()
        
    }
    
    //获取验证码
    func getCode() {
        
        let cuHTTP = CUHTTP.instance()
        
        let urlString = "code"
        
        
        var parameters: [String: Any]
        
        parameters = [
            "username" : username,
            "phone" : phoneView.text,
            "cuntryCode" : countryCode.text!.replacingOccurrences(of: "+", with: "", options: .literal, range: nil),
            "registerType" : "updatePhone",
        ]
        
        print(parameters)
        
        cuHTTP.makePostData(url: urlString, parameters: parameters,
                            success: {response in
                                print(response?.response?.statusCode ?? "??")      //成功时，返回200
        } ,
                            failure: {response in
                                self.myAlert(message000: EnStatic.getWord(keyWord: "get code failed"))
        }
        )

        
        
    }
    
    //提交验证码和新手机号信息
    func postCode() {
        
        phoneCode = phoneCodeView.text!
        
        let cuHTTP = CUHTTP.instance()
        
        let urlString = "register"
        
        var parameters: [String: Any]
        
        parameters = [
            "username" : username,
            "phone" :  phoneView.text!,
            "countryCode":countryCode.text!.replacingOccurrences(of: "+", with: "", options: .literal, range: nil),
            "code" : phoneCode,
            "registerType" : "updatePhone",
        ]
        
        print(parameters)
        
        cuHTTP.makePostData(url: urlString, parameters: parameters,
                            success: {response in
                                print(response?.response?.statusCode ?? "??")      //成功时，返回200
                                if let owningNavigationController = self.navigationController{
                                    owningNavigationController.popViewController(animated: true)
                                }else {
                                    fatalError("The ViewController is not inside a navigation controller.")
                                }
        } ,
                            failure: {response in
                                self.myAlert(message000: EnStatic.getWord(keyWord: "save failed"))
        }
        )
        
    }
    
    //获取旧的Profile信息
    func getProfile() {
        
        var urlString : String = ""
        
        urlString = "profile?username=" + loginOwner
        
        let cuHTTP = CUHTTP.instance()
        
        cuHTTP.makeGetData(url: urlString, success: {response in
            print("Response String: \(String(describing: response?.result.value))")
            print(response?.response?.statusCode ?? "??")      //成功时，返回200
            if let value = response?.result.value {
                let data = value.data(using: String.Encoding.utf8)! as NSData
                let json = try? JSONSerialization.jsonObject(with: data as Data,
                                                             options:.allowFragments) as! [String: Any]
                print(json ?? "??")
                let allEvents = json!["user"] as Any
                print(allEvents)
                
                let loopE = allEvents as! [String: Any]
                if let tmpStr0 = loopE["username"] {
                    if let tmpStr1 = (tmpStr0 as? String) {
                        self.username = tmpStr1
//                        self.countryCode.text = self.username
                    }
                }
                
                self.updateSaveButtonState()
                
            }
        },
                           failure:{ response in
                            print(response ?? " ")
                            self.myAlert(message000: EnStatic.getWord(keyWord: "get data failed"))
        }
        )
        
    }
    
    // Disable the Save button if the necessary field is empty.
    private func updateSaveButtonState() {
        let phone =  phoneView.text ?? ""
        let code =  phoneCodeView.text ?? ""
        let ifEnable = !phone.isEmpty && !code.isEmpty
        navigationItem.rightBarButtonItem?.isEnabled = ifEnable
    }
    
    //MARK: UITextFieldDelegate
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        // Disable the Save button while editing.
        navigationItem.rightBarButtonItem?.isEnabled = false
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        updateSaveButtonState()
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        // Hide the keyboard.
        textField.resignFirstResponder()
        return true
    }
    
    // MARK: - 重新定义各个显示控件的尺寸、位置、颜色、形状等属性
    func adapterUIAttribute() {
        
        var tmpY = 0
        var tmpWidth = 0
        var labelWidth = 0
        
        let tmpHeight = 30
        let fromX = 20
        
        let navigationBarHeight = 40
        let toolBarHeight = 60
        
        //最小的iphone宽度也不会越界，即verticalAdd一定大于零
        let verticalAdd = (screenHeight - screenY - toolBarHeight - 12 * tmpHeight)/12
        
        //字号
        let funtSize : CGFloat = 14.0
        
        //边框宽度和圆角半径
        let tmpBorder : CGFloat = 1.0
        let tmpCornerRadius : CGFloat = 4.0
        
        //重新定义各个控件的尺寸
        tmpY = screenY + navigationBarHeight + verticalAdd
        labelWidth = 90
        tmpWidth = tmpHeight * 2
        
        tmpWidth = screenWidth - (3 * fromX) - labelWidth
        tmpY = screenY + navigationBarHeight + 3 * verticalAdd + 3 * tmpHeight
        countryCodeLabel.frame = CGRect(x: fromX, y: tmpY, width: labelWidth, height: tmpHeight)
        countryCodeLabel.text = EnStatic.getWord(keyWord: "Country Code")
        countryCodeLabel.textColor = UIColor.black
        countryCodeLabel.font=UIFont.systemFont(ofSize: funtSize)
        
        countryCode.frame = CGRect(x: (fromX + labelWidth + 10), y: tmpY, width: tmpWidth, height: tmpHeight)
//        countryCode.setLeftPaddingPoints(5)
//        countryCode.setRightPaddingPoints(5)
        //根据用户所在国家设置初始值。需要找到country code列表
        countryCode.text = "+86".localized()
        countryCode.font = UIFont.systemFont(ofSize: funtSize)
        countryCode.layer.borderWidth = tmpBorder
        countryCode.layer.cornerRadius = tmpCornerRadius
        
        tmpY = screenY + navigationBarHeight + 4 * verticalAdd + 4 * tmpHeight
        prephoneLabel.frame = CGRect(x: fromX-8, y: tmpY+((tmpHeight-0)/2), width: 6, height: 6)
        prephoneLabel.text = "*"
        prephoneLabel.textColor = UIColor.red
        prephoneLabel.font=UIFont.systemFont(ofSize: funtSize)
         
        phoneLabel.frame = CGRect(x: fromX, y: tmpY, width: labelWidth, height: tmpHeight)
        phoneLabel.text = EnStatic.getWord(keyWord: "Phone")
        phoneLabel.textColor = UIColor.black
        phoneLabel.font=UIFont.systemFont(ofSize: funtSize)
         
        phoneView.frame = CGRect(x: (fromX + labelWidth + 10), y: tmpY, width: tmpWidth - 100, height: tmpHeight)
//        phoneView.setLeftPaddingPoints(5)
//        phoneView.setRightPaddingPoints(5)
        phoneView.text = phone
        phoneView.font = UIFont.systemFont(ofSize: funtSize)
        phoneView.layer.borderWidth = tmpBorder
        phoneView.layer.cornerRadius = tmpCornerRadius
         
        phoneCodeView.frame = CGRect(x: (fromX + labelWidth + 10 + tmpWidth - 80), y: tmpY, width: 80, height: tmpHeight)
//        phoneCodeView.setLeftPaddingPoints(5)
//        phoneCodeView.setRightPaddingPoints(5)
        phoneCodeView.text = phoneCode
        phoneCodeView.placeholder = "code"
        phoneCodeView.font = UIFont.systemFont(ofSize: funtSize)
        phoneCodeView.layer.borderWidth = tmpBorder
        phoneCodeView.layer.cornerRadius = tmpCornerRadius
         
        tmpY = screenY + navigationBarHeight + 5 * verticalAdd + 5 * tmpHeight
        sendButtonPhone.frame = CGRect(x: (fromX + labelWidth + 10), y: tmpY, width: tmpWidth, height: tmpHeight)
        sendButtonPhone.backgroundColor = UIColor.blue
        sendButtonPhone.setTitleColor(UIColor.white, for: .normal)
        sendButtonPhone.layer.borderWidth = tmpBorder
        sendButtonPhone.layer.cornerRadius = tmpCornerRadius
        sendButtonPhone.setTitle(EnStatic.getWord(keyWord: "get code"), for: .normal)
        sendButtonPhone.titleLabel?.font = UIFont(descriptor: UIFontDescriptor(), size: 12.0)
        sendButtonPhone.addTarget(self, action: #selector(sendButtonPhoneClick), for: .touchUpInside)
        
        self.view.addSubview(countryCodeLabel)
        self.view.addSubview(countryCode)
        self.view.addSubview(prephoneLabel)
        self.view.addSubview(phoneLabel)
        self.view.addSubview(phoneView)
        self.view.addSubview(phoneCodeView)
        self.view.addSubview(sendButtonPhone)
        
    }
    
}

/// Extend UITextView and implemented UITextViewDelegate to listen for changes
extension UITextView: UITextViewDelegate {
    
    /// Resize the placeholder when the UITextView bounds change
    override open var bounds: CGRect {
        didSet {
            self.resizePlaceholder()
        }
    }
    
    /// The UITextView placeholder text
    public var placeholder: String? {
        get {
            var placeholderText: String?
            
            if let placeholderLabel = self.viewWithTag(100) as? UILabel {
                placeholderText = placeholderLabel.text
            }
            
            return placeholderText
        }
        set {
            if let placeholderLabel = self.viewWithTag(100) as! UILabel? {
                placeholderLabel.text = newValue
                placeholderLabel.sizeToFit()
            } else {
                self.addPlaceholder(newValue!)
            }
        }
    }
    
    /// When the UITextView did change, show or hide the label based on if the UITextView is empty or not
    ///
    /// - Parameter textView: The UITextView that got updated
    public func textViewDidChange(_ textView: UITextView) {
        if let placeholderLabel = self.viewWithTag(100) as? UILabel {
            //            placeholderLabel.isHidden = self.text.characters.count > 0
            placeholderLabel.isHidden = !self.text.isEmpty
        }
    }
    
    /// Resize the placeholder UILabel to make sure it's in the same position as the UITextView text
    private func resizePlaceholder() {
        if let placeholderLabel = self.viewWithTag(100) as! UILabel? {
            let labelX = self.textContainer.lineFragmentPadding
            let labelY = self.textContainerInset.top - 2
            let labelWidth = self.frame.width - (labelX * 2)
            let labelHeight = placeholderLabel.frame.height
            
            placeholderLabel.frame = CGRect(x: labelX, y: labelY, width: labelWidth, height: labelHeight)
        }
    }
    
    /// Adds a placeholder UILabel to this UITextView
    private func addPlaceholder(_ placeholderText: String) {
        let placeholderLabel = UILabel()
        
        placeholderLabel.text = placeholderText
        placeholderLabel.sizeToFit()
        
        placeholderLabel.font = self.font
        placeholderLabel.textColor = UIColor.lightGray
        placeholderLabel.tag = 100
        
        //        placeholderLabel.isHidden = self.text.characters.count > 0
        placeholderLabel.isHidden = !self.text.isEmpty
        
        self.addSubview(placeholderLabel)
        self.resizePlaceholder()
        self.delegate = self
    }

}
